#import "UpgradeLibrary.h"
#import "WatermarkView.h"
#import <React/RCTBridgeModule.h>

@implementation UpgradeLibrary

RCT_EXPORT_MODULE()

RCT_EXPORT_METHOD(doNewVersionUpdate:(int)isForce
                  :(NSString*)versionUrl
                  :(NSString*)versionName
                  :(NSString*)versionDesc
                  :(RCTPromiseResolveBlock)resolve
                  :(RCTPromiseRejectBlock)reject)
{
       dispatch_async(dispatch_get_main_queue(), ^{
         //UIViewController *presentingController = RCTPresentedViewController();
         
         UIViewController *rootViewController = [[UIApplication sharedApplication] keyWindow].rootViewController;
           
           UIViewController *presentingController = rootViewController;

         UIAlertController *alertText = [UIAlertController alertControllerWithTitle:@"更新提醒" message:versionDesc preferredStyle:UIAlertControllerStyleAlert];
         UIView *subView1 = alertText.view.subviews[0];
         UIView *subView2 = subView1.subviews[0];
         UIView *subView3 = subView2.subviews[0];
         UIView *subView4 = subView3.subviews[0];
         UIView *subView5 = subView4.subviews[0];
         UILabel *messageLabel = nil;
         if ([[UIDevice currentDevice].systemVersion floatValue] >= 12.0f)
         {
           messageLabel = subView5.subviews[2];
         } else {
           messageLabel = subView5.subviews[1];
         }
         if(messageLabel)
           messageLabel.textAlignment = NSTextAlignmentLeft;
         //增加按钮
         if(isForce == 0) {
           [alertText addAction:[UIAlertAction actionWithTitle:@"稍后更新" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
             resolve(@[@"negative"]);
           }]];
         }
         [alertText addAction:[UIAlertAction actionWithTitle:@"立即更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
           Class isAllow = NSClassFromString(@"SKStoreProductViewController");
           if (isAllow != nil && ![versionUrl hasPrefix:@"http"]) {
             SKStoreProductViewController *storeProductVC = [[SKStoreProductViewController alloc] init];
             storeProductVC.delegate = self;
             NSDictionary *dic = [NSDictionary dictionaryWithObject:versionUrl forKey:SKStoreProductParameterITunesItemIdentifier];
             [storeProductVC loadProductWithParameters:dic completionBlock:^(BOOL result, NSError * _Nullable error) {
               if(error) {
                 resolve(@[@"error"]);
                 [rootViewController dismissViewControllerAnimated:YES completion:nil];
               } else {
                 resolve(@[@"positive"]);
               }
             }];
             [rootViewController presentViewController:storeProductVC animated:YES completion:nil];
           } else {
            if(![versionUrl hasPrefix:@"http"]) {
                NSURL *appStoreUrl = [NSURL URLWithString:[NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/id%@", versionUrl]];
                [[UIApplication sharedApplication] openURL:appStoreUrl];
            } else {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:versionUrl]];
            } 
            resolve(@[@"positive"]);
           }
         }]];

         [presentingController presentViewController:alertText animated:YES completion:nil];
       });
}

- (void)productViewControllerDidFinish:(SKStoreProductViewController *)viewController {
  [viewController dismissViewControllerAnimated:YES completion:NULL];
}

RCT_EXPORT_METHOD(showWatermarkView:(NSString *)text) {
  dispatch_async(dispatch_get_main_queue(), ^{
    UIApplication *application = [UIApplication sharedApplication];
    UIViewController *rootViewController = [[UIApplication sharedApplication] keyWindow].rootViewController;
    UIView* rootView = rootViewController.view;
    UIView* subviews = [rootView viewWithTag:1000];
    [subviews removeFromSuperview];

    WatermarkView * markView =  [[WatermarkView alloc] initWithFrame:rootViewController.view.bounds WithText: text];
    markView.tag = 1000;
    [rootViewController.view addSubview:markView];
  });
}

RCT_EXPORT_METHOD(openSettingsActivity:(RCTResponseSenderBlock)callback)
{
  NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
  dispatch_async(dispatch_get_main_queue(), ^{
    if([[UIApplication sharedApplication] openURL:url]) {
      [[UIApplication sharedApplication] openURL:url];
      callback(@[@true]);
    } else {
      callback(@[@false]);
    }
  });
}

@end
